import Vue from 'vue';
import VueRouter from 'vue-router';
// 引入组件
import Login from '../views/login';
import Layout from '../views/layout';
import { getToken } from '../utils/token';
import Chart from '../views/layout/chart';
import User from '../views/layout/user';
import Enterprise from '../views/layout/enterprise';
import Question from '../views/layout/question';
import Subject from '../views/layout/subject';
Vue.use(VueRouter);

const router = new VueRouter({
	routes: [
		{
			path: '/',
			redirect: '/login', // 重定向:重新指向其它path,会改变网址
		},
		{
			path: '*',
			redirect: '/login',
		},
		{
			path: '/login', // 登录页
			component: Login,
		},
		{
			path: '/layout', // 首页
			component: Layout,
			children: [
				// 子路由中的path前面不要加 /
				{ path: 'chart', component: Chart },
				{ path: 'user', component: User },
				{ path: 'enterprise', component: Enterprise },
				{ path: 'question', component: Question },
				{ path: 'subject', component: Subject },
			],
		},
	],
});

// 解决路由重复报错的问题
// const originalPush = VueRouter.prototype.push;
// VueRouter.prototype.push = function push(location) {
// 	return originalPush.call(this, location).catch((err) => err);
// };


// beforeEach 导航守卫
// to 去往何处
// from 从何而来
// next 控制去不去或者去到哪里, 并且必须要调用, 否则就会一直卡这里
// next() 如果里面不加任何参数, 就是正常的跳转到下一个页面
// next如果里面加了参数, 就是跳转到指定的页面

// 访问的白名单, 可以直接通行
const whiteList = ['/login'];
router.beforeEach((to, from, next) => {
	// 访问的路径在白名单
	if (whiteList.includes(to.path)) {
		next();
	} else {
		if (getToken()) {
			next();
		} else {
			next('/login');
		}
	}
});

export default router;
